package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.dao.CheckItemDao;
import com.itheima.health.dao.SetmeaDao;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.result.PageResult;
import com.itheima.health.result.QueryPageBean;
import com.itheima.health.service.CheckGroupService;
import com.itheima.health.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 检查组管理
 */

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmeaDao setmeaDao;

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        // 分页查询数据库
        Page<Setmeal> page = setmeaDao.findByCondition(queryPageBean.getQueryString());
        //封装分页数据
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增
     * @param setmeal
     * @param checkgroupIds
     */
    @Transactional
    public void add(Setmeal setmeal, List<Integer> checkgroupIds) {
        log.info("[套餐管理-添加]data：{}", setmeal);
        setmeaDao.add(setmeal);
        if(checkgroupIds != null && checkgroupIds.size() > 0){
            //绑定套餐和检查组的多对多关系
            setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
    }

    private void setSetmealAndCheckGroup(Integer id, List<Integer> checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",id);
            map.put("checkgroup_id",checkgroupId);
            setmeaDao.setSetmealAndCheckGroup(map);
        }
    }

    /**
     * 体检套餐
     * @return
     */
    public List<Setmeal> findAll() {
        return setmeaDao.findAll();
    }

    /**
     * 体检套餐 //根据id查询套餐信息
     * @param id
     * @return
     */
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmeaDao.findById(id);
        return setmeal;
    }
}